package com.dify.tool.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dify.tool.api.dto.DifyMessageSendDTO;
import com.dify.tool.api.dto.TenderRecordDTO;
import com.dify.tool.api.vo.TenderRecordStatisticsVO;
import com.dify.tool.api.vo.TenderRecordVO;
import com.dify.tool.common.constant.DifyConstants;
import com.dify.tool.common.constant.ErrorStatus;
import com.dify.tool.common.exception.BizException;
import com.dify.tool.common.utils.DifyApiUtils;
import com.dify.tool.common.utils.DocTemplateUtils;
import com.dify.tool.dal.entity.TechnicalGenerateRecord;
import com.dify.tool.dal.entity.TenderRecord;
import com.dify.tool.dal.mapper.TechnicalGenerateRecordMapper;
import com.dify.tool.dal.mapper.TenderRecordMapper;
import com.dify.tool.service.ITenderRecordService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 代码生成业务表 服务实现类
 * </p>
 *
 * @author shl
 * @since 2025-06-03
 */
@Slf4j
@Service
public class TenderRecordServiceImpl extends ServiceImpl<TenderRecordMapper, TenderRecord> implements ITenderRecordService {

    @Value("${dify.tender-matching-api-key}")
    private String tenderMatchingApiKey;

    @Value("${dify.technical-solution-generate-api-key}")
    private String technicalSolutionGenerateApiKey;

    @Value("${dify.url}")
    private String url;

    @Value("${dify.file-url}")
    private String difyFileUrl;

    @Value("${dify.secret-key}")
    private String secretKey;

    @Resource
    TechnicalGenerateRecordMapper technicalGenerateRecordMapper;

    @Override
    public IPage<TenderRecordVO> pageList(Page page, TenderRecordDTO recordDTO) {
        return baseMapper.page(page, recordDTO);
    }

    @Override
    public TenderRecordStatisticsVO statistics(TenderRecordDTO query) {
        return baseMapper.statistics();
    }

    @Override
    public String technicalSolutionGenerate(Long id) {
        TenderRecord info = getById(id);
        String eventData = DifyApiUtils.post(url + DifyConstants.SEND_CHAT, technicalSolutionGenerateApiKey, new DifyMessageSendDTO(info.getContent()));
        for (JSONObject event : DifyApiUtils.parseEvents(eventData)) {
            if (DifyConstants.EVENT_MESSAGE_END.equals(event.getStr("event"))) {
                JSONArray data = event.getJSONArray("files");
                JSONObject fileInfo = data.getJSONObject(0);
                String fileUrl = fileInfo.getStr("url");
                //生成记录保存  消息ID  文件ID  文件扩展名 招标信息ID
                TechnicalGenerateRecord generateRecord = new TechnicalGenerateRecord();
                generateRecord.setTenderRecordId(id);
                generateRecord.setExtension(fileInfo.getStr("extension"));
                generateRecord.setFileId(fileInfo.getStr("related_id"));
                generateRecord.setConversationId(event.getStr("conversation_id"));
                generateRecord.setMessageId(event.getStr("message_id"));
                technicalGenerateRecordMapper.insert(generateRecord);
                return difyFileUrl + fileUrl;
            }
        }
        return "";
    }

    @Override
    public String getFileUrlByFileId(String fileId, String extension) {
        return DifyApiUtils.getSignedFileUrl(fileId, extension, difyFileUrl, secretKey);
    }

    @XxlJob("autoQualificationMatch")
    public void autoQualificationMatch() {
        boolean queryFlag = true;
        int index = 1;
        int count = 0;
        while (queryFlag) {
            // 1. 招标公告接口地址
            String apiUrl = "http://cqgsbid.cegc.com.cn:7900/api/home/getBiddingCommonDtl";
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpPost httpPost = getHttpPost(apiUrl, index);
                try (CloseableHttpResponse pageResponse = httpClient.execute(httpPost)) {
                    HttpEntity entity = pageResponse.getEntity();
                    JSONObject responseBody = JSONUtil.parseObj(EntityUtils.toString(entity));
                    JSONArray recordList = responseBody.getJSONObject("data").getJSONArray("records");
                    if (ObjectUtils.isEmpty(recordList) || count >= 10) {
                        queryFlag = false;
                    }
                    for (int i = 0; i < recordList.size(); i++) {
                        JSONObject jsonObject = recordList.getJSONObject(i);
                        String title = jsonObject.getStr("title");
                        LambdaQueryWrapper<TenderRecord> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(TenderRecord::getProjectName, title);
                        Long num = baseMapper.selectCount(queryWrapper);
                        if (num == 0) {
                            String pubTime = jsonObject.getStr("pubTime");
                            JSONObject attacheFileList = jsonObject.getJSONArray("attacheFileList").getJSONObject(0);
                            String fileId = attacheFileList.getStr("fileId");
                            String fileName = attacheFileList.getStr("fileName");
                            log.info("当前项目：{}，文件ID：{}，文件名：{}", title, fileId, fileName);
                            String fileUrl = "http://cqgsbid.cegc.com.cn:7900/api/common/downBidFile/" + fileId;
                            String content = extractTextFromFileUrl(fileUrl, fileName);
                            log.info("项目：{}，内容：{}", title, content);
                            if (ObjectUtil.isNotEmpty(content) && !content.trim().isEmpty() && content.length() < 10000) {
                                //调用工作流进行资质匹配，获取匹配结果以及匹配明细
                                String eventData = DifyApiUtils.post(url + DifyConstants.SEND_CHAT, tenderMatchingApiKey, new DifyMessageSendDTO(content));
                                log.info("调用结果：{}", eventData);
                                for (JSONObject event : DifyApiUtils.parseEvents(eventData)) {
                                    if (DifyConstants.EVENT_NODE_FINISHED.equals(event.getStr("event"))) {
                                        JSONObject data = event.getJSONObject("data");
                                        if (DifyConstants.NODE_TYPE_PARA.equals(data.getStr("node_type"))) {
                                            JSONObject outputs = data.getJSONObject("outputs");
                                            // 提取 matchingDegree
                                            double matchingDegree = outputs.getDouble("matchingDegree");
                                            // 提取并解码 matchingDetail
                                            String matchingDetail = outputs.getStr("matchingDetail");
                                            String decodedDetail = DifyApiUtils.decodeUnicode(matchingDetail);
                                            // 提取招标截至时间
                                            String projectDeadline = outputs.getStr("projectDeadline");
                                            //保存记录
                                            TenderRecord record = new TenderRecord();
                                            record.setId(IdWorker.getId());
                                            record.setProjectName(title);
                                            record.setProjectSourceUrl("http://cqgsbid.cegc.com.cn:7900/#/web/biddingAnnouncement");
                                            record.setPublishTime(pubTime);
                                            record.setMatchingResult(decodedDetail);
                                            record.setMatchingDegree(matchingDegree);
                                            record.setProjectDeadline(projectDeadline);
                                            record.setContent(content);
                                            baseMapper.insert(record);
                                            count += 1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                throw new BizException(ErrorStatus.SYNC_INVITE_TENDERS_FILE_FAIL);

            }
            index += 1;
        }
    }

    private static HttpPost getHttpPost(String apiUrl, int index) throws JsonProcessingException {
        HttpPost httpPost = new HttpPost(apiUrl);
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Origin", "http://cqgsbid.cegc.com.cn:7900");
        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", index);
        params.put("pageSize", 10);
        params.put("status", "6");
        ObjectMapper mapper = new ObjectMapper();
        String jsonBody = mapper.writeValueAsString(params);
        httpPost.setEntity(new StringEntity(jsonBody, "UTF-8"));
        return httpPost;
    }

    public String extractTextFromFileUrl(String fileUrl, String fileName) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            try (CloseableHttpResponse fileResponse = httpClient.execute(new HttpGet(fileUrl))) {
                HttpEntity httpEntity = fileResponse.getEntity();
                try (InputStream inputStream = httpEntity.getContent()) {
                    return DocTemplateUtils.extractText(inputStream, FilenameUtils.getExtension(fileName));
                }
            }
        }
    }

}
